﻿using StorageApp.Utility;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows;

namespace StorageApp.Service
{
    [Serializable]
    public class SerialPortService  
    {
        /// <summary>事件聚合器</summary> 
        public SerialPort serialPort =   new SerialPort() { Handshake = Handshake.None };
        public string PortName="" ;
        public int BaudRate = 9600;
        public int DataBits = 8; 
        public SerialPortService(string portName)
        {
            PortName=portName; 
        }
        public SerialPortService()
        {
        }
        /// <summary>串口开始监听</summary>
        /// <param name="serialPort"></param>
        /// <param name="comPort"></param>
        public bool StartListening()
        {
            try {
                if (serialPort != null) {
                    if (serialPort.IsOpen) {
                        StopListening();
                    } 
                    if(PortName.Length == 0)
                    {
                        PortName= Method.IniReadValue("PortName");
                        if(PortName.Length == 0)
                        {
                            PortName = SerialPort.GetPortNames().First();
                        }
                       
                        Method.IniWrite("PortName", PortName);
                    }
                    // 配置串口
                 
                    serialPort.PortName = PortName;
                    serialPort.BaudRate = BaudRate;
                    serialPort.DataBits = DataBits; 
                    if (SerialPort.GetPortNames().Length > 0 && SerialPort.GetPortNames().Contains(PortName)) {
                        // 打开串口
                        serialPort.Open();

                        return true;
                    } else {
                        return false;
                    }
                }
                else {
                    return false;
                }
            }
            catch (Exception) {
                return false;
            }
        }

        /// <summary>串口关闭监听</summary>
        /// <param name="serialPort"></param>
        public bool StopListening()
        {
            if (serialPort != null && serialPort.IsOpen) {
                try {
                    // 关闭串口
                    serialPort.Dispose();
                    serialPort.Close();

                    return true;
                }
                catch (Exception) {
                    throw;
                }
            }

            return false;
        }

        /// <summary>获取串口连接状态</summary>
        /// <param name="serialPort"></param>
        /// <returns></returns>
        public bool GetConnectionStatus(SerialPort serialPort) => serialPort != null && serialPort.IsOpen;

        /// <summary>接收buffer处理</summary>
        /// <param name="serialPort"></param>
        /// <param name="comPort"></param>
        
 
    }
}
